package com.it.travel01.service.impl;

import com.it.travel01.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service("messageService")
public class MessageServiceImpl implements MessageService {

    /**
     * 注入发送邮件对象
     */
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 注入发送者地址
     */
    @Value("${spring.mail.username}")
    private String whoFrom;

    @Override
    public void sendMessage(String toWho, String subject, String context) throws MessagingException {
        //构建邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //构建邮件包装类，方便参数设置
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
        //设置mail发送方地址
        mimeMessageHelper.setFrom(whoFrom);
        //设置mail接收方地址
        mimeMessageHelper.setTo(toWho);
        //设置mail主题
        mimeMessageHelper.setSubject(subject);
        /**
         * 参数1：邮件正文
         * 参数2：true表示html格式
         */
        mimeMessageHelper.setText(context,true);
        javaMailSender.send(mimeMessage);


    }
}
